package cn.edu.xmist.supermarket.steam.controller;

import cn.edu.xmist.supermarket.steam.entity.ProductPO;
import cn.edu.xmist.supermarket.steam.service.OutputService;
import cn.edu.xmist.supermarket.steam.util.ObjtoLayJson;
import cn.edu.xmist.supermarket.steam.config.Vars;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/product")
public class OutputController {

  public static final String[] COLUMNS = {"id", "name", "price", "num", "houseCode", "supplierCode"};

  @Autowired private OutputService outputService;

  @RequestMapping("/list")
  public String list(Integer page, Integer limit) throws Exception {
    List<ProductPO> list = outputService.list();
    List<ProductPO> pageList = new ArrayList<>();
    for (int i = 0; i < list.size(); i++) {
      if (i >= (page - 1) * limit && i < page * limit) {
        pageList.add(list.get(i));
      }
    }
    return ObjtoLayJson.ListtoJson(pageList, COLUMNS);
  }

  @RequestMapping("/pageList")
  public String pageList(Integer page, Integer limit, ProductPO product) throws Exception {
    System.out.println(product.toString() + "1111");
    List<ProductPO> pageList = outputService.selectPage(product, page, limit);
    String[] column = {
      "id", "name", "price", "num", "houseCode", "supplierCode", "houseName", "supplierName"
    };
    return ObjtoLayJson.ListtoJson(pageList, column);
  }

  @RequestMapping("/saveOrUpdate")
  public String saveOrUpdate(ProductPO product) {
    Boolean flag = outputService.saveOrUpdate(product);
    return Vars.SUCCESS;
  }

  @RequestMapping("/deleteById")
  public String deleteById(Long id) {
    Boolean flag = outputService.removeById(id);
    return Vars.SUCCESS;
  }
}
